package com.zxq.web.notifyplatfrom.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxq.exchange.model.ExchangeDTO;
import com.zxq.exchange.register.INotifyPlatform;
import com.zxq.web.channel.SynchronismMessage;
import com.zxq.web.channel.TcpMessageChannel;
import com.zxq.web.channel.device.DeviceMessageServiceImpl;
import com.zxq.web.dto.PlatformCmdDTO;
import com.zxq.web.enums.EPlatformCmdType;
import com.zxq.web.iot.domain.IotCmd;
import com.zxq.web.iot.domain.IotDevice;
import com.zxq.web.iot.domain.IotPacket;
import com.zxq.web.iot.domain.IotProject;
import com.zxq.web.iot.service.impl.IotCmdServiceImpl;
import com.zxq.web.iot.service.impl.IotDeviceServiceImpl;
import com.zxq.web.iot.service.impl.IotPacketServiceImpl;
import com.zxq.web.iot.service.impl.IotProjectServiceImpl;
import com.zxq.web.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class GeneralNotifyPlatform implements INotifyPlatform {

    /**
     * 设备 -> 产品
     */
    @Autowired
    private IotDeviceServiceImpl iotDeviceService;

    /**
     * 产品 -> 协议包
     */
    @Autowired
    private IotProjectServiceImpl iotProjectService;

    /**
     * 协议包 -> 具体指令
     */
    @Autowired
    private IotPacketServiceImpl iotPacketService;

    /**
     * 具体指令 -> 指令解析流程
     */
    @Autowired
    private IotCmdServiceImpl iotCmdService;

    /**
     * 设备消息服务
     */
    @Autowired
    private DeviceMessageServiceImpl deviceMessageService;

    /**
     * 同步消息
     */
    @Autowired
    private SynchronismMessage synchronismMessage;

    /**
     * 消息翻译器
     */
    @Autowired
    private ITransformServiceImpl iTransformService;

    /**
     * tcp消息通道
     */
    @Autowired
    private TcpMessageChannel tcpMessageChannel;


    @Override
    public void notifyPlatform(ExchangeDTO exchangeDTO) {

        log.info("rec dev:" + exchangeDTO.toString());
        String devId = exchangeDTO.getDevId();
        String cmdHex = exchangeDTO.getCmdHex();
        IotDevice iotDeviceDo = new IotDevice();
        iotDeviceDo.setDevId(devId);
        List<IotDevice> iotDeviceDoResults = iotDeviceService.selectIotDeviceList(iotDeviceDo);
        if(iotDeviceDoResults.size() == 0) {
            log.warn(String.format("devId:{0} not register platform",devId));
            return;
        }
        IotDevice  iotDeviceDoResult = iotDeviceDoResults.get(0);
        IotProject iotProjectDo = iotProjectService.selectIotProjectById(iotDeviceDoResult.getProjectId());
        if(iotDeviceDo == null) {
            log.warn(String.format("devId:{0} belong product is delete",devId));
            return;
        }
        String token = iotProjectDo.getToken();
        Long utilsTime = iotProjectDo.getStartTime().getTime() + iotProjectDo.getDays() * 24 * 60 * 60 * 1000;
        if(System.currentTimeMillis() > utilsTime) {
            log.warn(String.format("devId:{0} belong product is expire",devId));
            return;
        }

        IotPacket iotPacketDo = iotPacketService.selectIotPacketById(iotProjectDo.getPacketId());
        if(iotPacketDo == null) {
            log.warn(String.format("devId:{0} belong packet is delete",devId));
            return;
        }

        Long packetId = iotPacketDo.getId();
        IotCmd iotCmdDo = new IotCmd();
        iotCmdDo.setPacketId(packetId);
        iotCmdDo.setCmdHex(cmdHex);
        //Sponsor  0 设备 1 平台
        iotCmdDo.setSponsor(0L);
        List<IotCmd> iotCmdResults = iotCmdService.selectIotCmdList(iotCmdDo);
        if(iotCmdResults.size() == 0) {
            log.warn(String.format("devId:{0} cmd({1}) not config",devId,cmdHex));
            return;
        }

        IotCmd iotCmdResult = iotCmdResults.get(0);
        /**
         * 0 指令，需要回复； 1 指令，不需要回复； 2 回复指令；
         */
        Long cmdType = iotCmdResult.getCmdType();
        EPlatformCmdType platformCmdType =  EPlatformCmdType.getType(cmdType.intValue());
        switch (platformCmdType) {
            case CMD: {
                deviceMessageService.deviceReport(exchangeDTO,iotProjectDo.getRequestUrl(),token);
                PlatformCmdDTO platformCmdDTO = synchronismMessage.waitCmdMessage(devId,iotCmdResult.getId());
                log.info("wait message:" + platformCmdDTO.toString());
                ExchangeDTO resultExchangeDTO = iTransformService.platTransform(platformCmdDTO);
                tcpMessageChannel.notifyPlatform(resultExchangeDTO);
            }
            break;
            case NOTICE: {
                deviceMessageService.deviceReport(exchangeDTO,iotProjectDo.getRequestUrl(),token);
            }
            break;
            case RESULT: {
                deviceMessageService.deviceResult(exchangeDTO);
            }
            break;
        }
    }

}
